// index.js
Page({
  data: {
    inputValue: '',
    messages: []
  },

  onLoad() {
    // 页面加载时获取聊天记录
    const messages = wx.getStorageSync('messages') || [];
    this.setData({ messages });
  },

  onInput(e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

  async sendMessage() {
    const { inputValue, messages } = this.data;
    if (!inputValue.trim()) return;

    // 更新聊天记录
    const userMessage = { text: inputValue, type: 'user' };
    this.setData({
      messages: [...messages, userMessage],
      inputValue: ''
    });
    this.saveMessages();

    // 调用AI接口获取回复
    const botResponse = await this.getAIResponse(inputValue);

    // 更新聊天记录
    const botMessage = { text: botResponse, type: 'bot' };
    this.setData({
      messages: [...this.data.messages, botMessage]
    });
    this.saveMessages();
  },

  async getAIResponse(query) {
    try {
      const response = await wx.request({
        url: 'https://api.openai.com/v1/engines/davinci-codex/completions',
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer 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'
        },
        data: {
          prompt: query,
          max_tokens: 150
        }
      });
      return response.data.choices[0].text.trim();
    } catch (error) {
      console.error('Error fetching AI response:', error);
      return 'Sorry, something went wrong.';
    }
  },

  handleCardTap(e) {
    const { text } = e.currentTarget.dataset;
    this.setData({
      inputValue: text
    });
    this.sendMessage();
  },

  saveMessages() {
    wx.setStorageSync('messages', this.data.messages);
  }
});